/* eslint-disable default-case */
import { message } from 'antd';
import {
  getPageList,
  countPla,
  deleteMul,
  deleteBankMul,
  updateStatus,
  getSuppInfo,
  insert,
  insertPla,
  getInfo,
  getNameList,
  getSupplierList,
  updatePla,
  update,
  queryNmArea,
  queryNmAreaByParent,
  getBankList,
  getBankInfo,
  insertBankInfo,
  updateBankInfo,
  getContactList,
  deleteContactList,
  getContactInfo,
  insertContactsInfo,
  updateContactsInfo,
  getvatCoprName,
  getTaxerName,
  getInvoiceList,
  deleteInvoiceMul,
  getInvoiceInfo,
  insertInvoiceInfo,
  updateInvoiceInfo,
  fetchMailList,
  delMailMul,
  getMailInfo,
  insertMailInfo,
  updateMailInfo,
  getDownloadInfoSupp,
  uploadFileSupp,
  getMgrSuppList,
  getMgrSuppListByUser,
} from '@/services/supplymanage';
import * as service from '@/services/socket';
import { SocketActions, batchTaskFactory } from '@/models/socket';
import { delay } from '@/utils/dva';
// 非常重要属性
const namespace = 'suppliermaintenance';

export default {
  namespace,
  state: {
    pageData: {
      list: [],
      pagination: {
        current: 1,
        pageSize: 10,
        total: 10,
      },
    },
    formFieldsValue: {},
    expandForm: false,
    activeKey: '1',
    resultInfo: {
      // 结果数据必传
      taskCount: 0, // 导入数据
      successCount: 0, // 成功数据
      errorCount: 0, // 失败数据
      batchNo: '', // 批次号
      errorParams: null, // 下载错误数据参数
    },
    showProgress: false,
    currentStep: 0,
    progressPercent: 0,
    valuesArr: ['suppCode', 'suppId', 'creTime', 'status'],
    supplyNameList: [],
  },
  effects: {
    // 获取列表
    *fetchList({ payload }, { call, put }) {
      const response = yield call(getPageList, payload);
      const {
        pageArg: { currentPage, pageSize },
      } = payload;
      if (response.success) {
        yield put({
          type: 'getList',
          payload: {
            data: response.data,
            currentPage,
            pageSize,
          },
        });
      } else {
        message.warning(`${response.message || '服务端错误！'}`);
      }
    },
    *countPla({ payload, callback }, { call }) {
      const response = yield call(countPla, payload);
      callback(response);
    },
    *deleteMul({ payload, callback }, { call }) {
      const response = yield call(deleteMul, payload);
      callback(response);
    },
    *deleteBankMul({ payload, callback }, { call }) {
      const response = yield call(deleteBankMul, payload);
      callback(response);
    },
    *updateStatus({ payload, callback }, { call }) {
      const response = yield call(updateStatus, payload);
      callback(response);
    },
    *getSuppInfo({ payload, callback }, { call }) {
      const response = yield call(getSuppInfo, payload);
      callback(response);
    },
    *insert({ payload, callback }, { call }) {
      const response = yield call(insert, payload);
      callback(response);
    },
    *insertPla({ payload, callback }, { call }) {
      const response = yield call(insertPla, payload);
      callback(response);
    },
    *fetchInfo({ payload, callback }, { call }) {
      const response = yield call(getInfo, payload);
      callback(response);
    },
    *fetchNameList({ payload, callback }, { call }) {
      const response = yield call(getNameList, payload);
      callback(response);
    },
    *fetchSuppList({ payload, callback }, { call }) {
      const response = yield call(getSupplierList, payload);
      callback(response);
    },
    *updatePla({ payload, callback }, { call }) {
      const response = yield call(updatePla, payload);
      callback(response);
    },
    *update({ payload, callback }, { call }) {
      const response = yield call(update, payload);
      callback(response);
    },
    *queryNmArea({ payload, callback }, { call }) {
      const response = yield call(queryNmArea, payload);
      callback(response);
    },
    *queryNmAreaByParent({ payload, callback }, { call }) {
      const response = yield call(queryNmAreaByParent, payload);
      callback(response);
    },
    *fetchBankList({ payload, callback }, { call }) {
      const response = yield call(getBankList, payload);
      callback(response);
    },
    *getBankInfo({ payload, callback }, { call }) {
      const response = yield call(getBankInfo, payload);
      callback(response);
    },
    *insertBankInfo({ payload, callback }, { call }) {
      const response = yield call(insertBankInfo, payload);
      callback(response);
    },
    *updateBankInfo({ payload, callback }, { call }) {
      const response = yield call(updateBankInfo, payload);
      callback(response);
    },
    *fetchContactList({ payload, callback }, { call }) {
      const response = yield call(getContactList, payload);
      callback(response);
    },
    *deleteContactList({ payload, callback }, { call }) {
      const response = yield call(deleteContactList, payload);
      callback(response);
    },
    *getContactInfo({ payload, callback }, { call }) {
      const response = yield call(getContactInfo, payload);
      callback(response);
    },
    *insertContactsInfo({ payload, callback }, { call }) {
      const response = yield call(insertContactsInfo, payload);
      callback(response);
    },
    *updateContactsInfo({ payload, callback }, { call }) {
      const response = yield call(updateContactsInfo, payload);
      callback(response);
    },
    *getvatCoprName({ payload, callback }, { call }) {
      const response = yield call(getvatCoprName, payload);
      callback(response);
    },
    *getTaxerName({ payload, callback }, { call }) {
      const response = yield call(getTaxerName, payload);
      callback(response);
    },
    *getInvoiceList({ payload, callback }, { call }) {
      const response = yield call(getInvoiceList, payload);
      callback(response);
    },
    *deleteInvoiceMul({ payload, callback }, { call }) {
      const response = yield call(deleteInvoiceMul, payload);
      callback(response);
    },
    *getInvoiceInfo({ payload, callback }, { call }) {
      const response = yield call(getInvoiceInfo, payload);
      callback(response);
    },
    *insertInvoiceInfo({ payload, callback }, { call }) {
      const response = yield call(insertInvoiceInfo, payload);
      callback(response);
    },
    *updateInvoiceInfo({ payload, callback }, { call }) {
      const response = yield call(updateInvoiceInfo, payload);
      callback(response);
    },
    *fetchMailList({ payload, callback }, { call }) {
      const response = yield call(fetchMailList, payload);
      callback(response);
    },
    *delMailMul({ payload, callback }, { call }) {
      const response = yield call(delMailMul, payload);
      callback(response);
    },
    *getMailInfo({ payload, callback }, { call }) {
      const response = yield call(getMailInfo, payload);
      callback(response);
    },
    *insertMailInfo({ payload, callback }, { call }) {
      const response = yield call(insertMailInfo, payload);
      callback(response);
    },
    *updateMailInfo({ payload, callback }, { call }) {
      const response = yield call(updateMailInfo, payload);
      callback(response);
    },
    // 获取下载模板信息
    *getDownloadInfo({ payload }, { call, put }) {
      const response = yield call(getDownloadInfoSupp, payload);
      yield put({
        type: 'updateQuery',
        payload,
      });
      if (response.success) {
        const fileInfo = response.data.split('|');
        yield put({
          type: 'publicdata/setFileDownload',
          payload: { fileId: fileInfo[0], fileName: fileInfo[1] },
        });
      } else {
        message.warning(`${response.message || '服务端错误：获取下载模板失败！'}`);
      }
    },
    // 上传文件:批量进度
    *uploadFileWithProgress({ payload }, { call, put }) {
      try {
        const response = yield call(uploadFileSupp, payload);
        if (response.success) {
          // 不是100表示需要走队列
          if (response.data && response.data.successProp !== 100) {
            const { batchId } = response.data;
            const batchTask = batchTaskFactory(batchId, namespace, 'handleBatchTask');

            yield put.resolve({
              type: `socket/${SocketActions.subSocketChannel}`,
              payload: {
                batchTask,
              },
            });
            // 订阅成功后再触发进度条
            yield put({
              type: 'updateModelData',
              payload: { showProgress: true },
            });
          } else {
            yield put({
              type: 'handleBatchTask',
              payload: response.data,
            });
          }
        } else {
          message.warning(response.message || '上传文件错误：服务器端错误');
        }

        // 无需返回response对象
      } catch (e) {
        console.error(e);
      }
    },
    *handleBatchTask({ payload }, { put, select }) {
      const state = yield select(s => s.suppliermaintenance);
      let { showProgress, resultInfo, currentStep } = state;
      showProgress = true;
      if (payload.successProp >= 100) {
        // 下载错误数据：地址
        resultInfo.errorUrl = '/mgrApi/supplier/dowoloadErrorExist';
        // 下载错误数据：参数
        resultInfo.errorParams = {
          batchId: payload.batchId,
        };
        resultInfo = { ...resultInfo, ...payload };
        currentStep += 1;
        showProgress = false;
        // 先更新进度
        yield put({
          type: 'updateBatchTask',
          payload: {
            progressPercent: payload.successProp,
            resultInfo,
          },
        });
        yield delay(3000);
        // 再更新状态
        yield put({
          type: 'updateBatchTask',
          payload: {
            currentStep,
            showProgress,
          },
        });
      } else {
        yield put({
          type: 'updateBatchTask',
          payload: { progressPercent: payload.successProp, resultInfo },
        });
      }
    },
    *getMgrSuppList({ payload }, { call, put }) {
      const res = yield call(getMgrSuppList, payload);
      if (res.success) {
        yield put({
          type: 'updateModelData',
          payload: { supplyNameList: res.data },
        });
      } else {
        message.warning(res.message || '服务端错误');
      }
    },
    *getMgrSuppListByUser({ payload }, { call, put }) {
      const res = yield call(getMgrSuppListByUser, payload);
      if (res.success) {
        yield put({
          type: 'updateModelData',
          payload: { supplyNameList: res.data },
        });
      } else {
        message.warning(res.message || '服务端错误');
      }
    },
  },

  reducers: {
    // 获取列表
    getList(
      state,
      {
        payload: { data, currentPage, pageSize },
      }
    ) {
      const list = Array.isArray(data.pageRecords) ? data.pageRecords : [];
      return {
        ...state,
        pageData: {
          list,
          pagination: { total: data.totalCount, current: currentPage, pageSize },
        },
      };
    },
    // 设置修改当前state数据
    updateModelData(state, { payload }) {
      return {
        ...state,
        ...payload,
      };
    },
    // 设置页签状态
    updateTabListQuery(state, { payload }) {
      return {
        ...state,
        ...payload,
      };
    },
    // 更新批量任务数据
    updateBatchTask(state, { payload }) {
      return {
        ...state,
        ...payload,
      };
    },
  },
  subscriptions: {
    socket({ dispatch }) {
      service.listen(async action => {
        // 判断是否自己命名空间的回调

        if (action.namespace === namespace) {
          switch (action.type) {
            case 'task':
              await dispatch({
                type: 'handleBatchTask',
                payload: action.data,
              });
              await dispatch({
                type: `socket/${SocketActions.handleUpdateBatchTask}`,
                payload: {
                  successProp: action.data.successProp,
                  batchId: action.data.batchId,
                },
              });
              // 全局保存
              dispatch({
                type: 'publicdata/updateBatchTaskData',
                payload: action.data,
              });
              break;
          }
        }
      }, namespace);
    },
  },
};
